/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: SNMPManager.java</p>
 *
 * @author zz
 * @date 2024/5/23
 * @version 1.0
 * History:
 * v1.0.0 2024/5/23 Create
 */
package com.jason.zax.controller;

/**
 * <p>Title: SNMPManager</p>
 * <p>Description: </p>
 *
 * @author zz
 */

import org.snmp4j.*;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SNMPManager {
    private static final int SNMP_PORT = 161;
    private static final String COMMUNITY = "public";

    public static List<NetworkDevice> discoverNetwork(String startIP, String community) throws IOException {
        List<NetworkDevice> devices = new ArrayList<>();
        TransportMapping transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        transport.listen();

        for (int i = 1; i <= 254; i++) {
            String ip = startIP.substring(0, startIP.lastIndexOf('.')) + "." + i;
            try {
                PDU pdu = new PDU();
                pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1.0"))); // sysDescr
                Address targetAddress = GenericAddress.parse("udp:" + ip + "/" + SNMP_PORT);
                CommunityTarget target = new CommunityTarget();
                target.setCommunity(new OctetString(community));
                target.setAddress(targetAddress);
                target.setRetries(2);
                target.setTimeout(1500);
                target.setVersion(SnmpConstants.version2c);

                ResponseEvent event = snmp.send(pdu, target);
                if (event != null && event.getResponse() != null) {
                    devices.add(new NetworkDevice(ip, community));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        snmp.close();
        return devices;
    }

    public static void main(String[] args) {
        try {
            discoverNetwork("172.16.20.36", "public");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

